package com.wsg.lightaccounting.Activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.wsg.lightaccounting.Model.Expenditure;
import com.wsg.lightaccounting.Model.Income;
import com.wsg.lightaccounting.PopupWindow.AccountPopupWindow;
import com.wsg.lightaccounting.Adapter.ExpenditureTypeGridAdapter;
import com.wsg.lightaccounting.Adapter.IncomeTypeAdapter;
import com.wsg.lightaccounting.PopupWindow.MarkPopupWindow;
import com.wsg.lightaccounting.Model.RecordManager;
import com.wsg.lightaccounting.R;
import com.wsg.lightaccounting.PopupWindow.SelectPicPopupWindow;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class AccountActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText editText;
    private GridView iconView;
    private ImageView icon_type;
    private ImageButton back, accept;
    private RadioButton expenditure,income;
    private Button date, account_book,account,mark;
    private TextView textView;
    private Button[] buttons;

    public static long account_id=0L,account_book_id=0L,type=0L;
    public static String mark_information = "";
    public static float money = 0f;
    public static Date date_information;

    private IncomeTypeAdapter incomeTypeAdapter;
    private ExpenditureTypeGridAdapter expenditureTypeGridAdapter;

    private DateFormat fmtDate = new java.text.SimpleDateFormat("yyyy-MM-dd");

    private Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
    private DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            //修改日历控件的年，月，日
            //这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
            dateAndTime.set(Calendar.YEAR, year);
            dateAndTime.set(Calendar.MONTH, monthOfYear);
            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            //将页面TextView的显示更新为最新时间
            upDateDate();

        }
    };

    private RecordManager recordManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_account);
        initView();
        initData();
    }


    private void initData(){
        account_id = 0L;
        account_book_id=0L;
        type=0L;
        mark_information = "";
        money = 0f;
        upDateDate();
    }
    private void initView() {
        editText = (EditText) findViewById(R.id.editText);
        iconView = (GridView) findViewById(R.id.gridView);
        date = (Button) findViewById(R.id.date);
        account_book = (Button) findViewById(R.id.account_book);
        icon_type = (ImageView) findViewById(R.id.Icon_type);
        back = (ImageButton) findViewById(R.id.back);
        expenditure = (RadioButton) findViewById(R.id.expenditure);
        income = (RadioButton) findViewById(R.id.income);
        account = (Button) findViewById(R.id.account);
        mark = (Button) findViewById(R.id.mark);
        textView = (TextView) findViewById(R.id.icon_name);
        accept = (ImageButton) findViewById(R.id.accept);
        recordManager = RecordManager.getRecordManager(this);

        buttons = new Button[16];
        for(int i=0; i<buttons.length; i++) {
                String buttonID = "btn" + (i+1) ;
                int resID = getResources().getIdentifier(buttonID, "id", "com.wsg.lightaccounting");
                buttons[i] = ((Button) findViewById(resID));
                buttons[i].setOnClickListener(this);
            }
        incomeTypeAdapter = new IncomeTypeAdapter(this);
        expenditureTypeGridAdapter = new ExpenditureTypeGridAdapter(this, RecordManager.expenditureTypes);

        editText.setInputType(InputType.TYPE_NULL);
        if(expenditure.isChecked()) {
            iconView.setAdapter(expenditureTypeGridAdapter);
        }
        else
        {
            iconView.setAdapter(incomeTypeAdapter);
        }
        accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addRecord();
                MainActivity.updateAllUI(AccountActivity.this);
                finish();
            }
        });
        iconView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                icon_type.setImageDrawable(view.findViewById(R.id.grid_icon).getBackground());
                textView.setText(((TextView)view.findViewById(R.id.grid_name)).getText());
                type = id;
            }
        });
        expenditure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!iconView.getAdapter().equals(expenditureTypeGridAdapter)){
                    iconView.setAdapter(expenditureTypeGridAdapter);
                    expenditureTypeGridAdapter.notifyDataSetChanged();
                }
            }
        });
        income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!iconView.getAdapter().equals(incomeTypeAdapter)){
                    iconView.setAdapter(incomeTypeAdapter);
                    incomeTypeAdapter.notifyDataSetChanged();
                }
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountActivity.this.finish();
            }
        });
        account_book.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAccountBookWindow();
            }
        });
        account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAccountWindow();
            }
        });
        mark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            showMarkWindow();
            }
        });
        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showDateWindow();
            }
        });

    }

    private void upDateDate() {
        date.setText(fmtDate.format(dateAndTime.getTime()));
        SimpleDateFormat formatter    =   new    SimpleDateFormat    ("yyyy-MM-dd HH:mm:ss");
        String datetime = String.valueOf(date.getText());
        if (datetime.equals(fmtDate.format(new Date(System.currentTimeMillis()))))
        {
            Date    curDate    =   new    Date(System.currentTimeMillis());//获取当前时间
            datetime    =    formatter.format(curDate);
        }
        else {
            datetime = datetime + " 23:59:59";
        }
        try {
            date_information = formatter.parse(datetime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void showMarkWindow(){
        MarkPopupWindow markPopupWindow = new MarkPopupWindow(AccountActivity.this,
                AccountActivity.this.findViewById(R.id.grid_linear_layout).getWidth(),AccountActivity.this.findViewById(R.id.grid_linear_layout).getHeight());
        markPopupWindow.showAtLocation(AccountActivity.this.findViewById(R.id.grid_linear_layout), Gravity.BOTTOM,0,0);
    }
    private void addRecord(){
        if (expenditure.isChecked()){
            Expenditure expenditure = new Expenditure(0L,money,date_information,account_book_id,account_id,0,type,mark_information);
            recordManager.addExpenditure(expenditure);
        }
        else {
            Income income = new Income(0L,money,date_information,account_book_id,account_id,type,mark_information);
            recordManager.addIncome(income);
        }
    }
    private void showAccountBookWindow(){
        SelectPicPopupWindow selectPicPopupWindow=new SelectPicPopupWindow(AccountActivity.this,
                AccountActivity.this.findViewById(R.id.keybored).getWidth(),AccountActivity.this.findViewById(R.id.keybored).getHeight());
        selectPicPopupWindow.showAsDropDown(AccountActivity.this.findViewById(R.id.choose));
    }

    private void showAccountWindow(){
        AccountPopupWindow accountPopupWindow= new AccountPopupWindow(AccountActivity.this,
                AccountActivity.this.findViewById(R.id.keybored).getWidth(),AccountActivity.this.findViewById(R.id.keybored).getHeight());
        accountPopupWindow.showAsDropDown(AccountActivity.this.findViewById(R.id.choose));
    }
    private void showDateWindow(){
        DatePickerDialog dateDlg = new DatePickerDialog(AccountActivity.this,
                d, dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH),
                dateAndTime.get(Calendar.DAY_OF_MONTH));
        dateDlg.show();
    }
    private void input(int i){
        String money = String.valueOf(editText.getText());
        if(money.equals("0.0"))
        {
            money = "";
        }
        money = money + i;
        editText.setText(money);
        if (money.indexOf('+') == -1 && money.indexOf('-') == -1 ) {
            this.money = Float.parseFloat(money);
        }
    }
    private void backSpace(){
        String money = String.valueOf(editText.getText());
        if(!money.equals("0.0") && money.length()!=0)
        {
            money = money.substring(0,money.length() - 1);
        }else if (money.length()==0){
            money = "0.0";
        }
        editText.setText(money);
        if(money.indexOf('+') == -1 && money.indexOf('-') == -1 )
        {
            if(!money.equals("")){
            this.money = Float.parseFloat(money);}
            else {
                this.money =0f;
            }
        }
    }
    private void clear(){
        String money = "0.0";
        editText.setText(money);
    }

    private void operation(char operation) {
        String money = String.valueOf(editText.getText());

        if (money.indexOf('+') == -1 && money.indexOf('-') == -1 ) {
            money = money + operation;
        }
        else{
            char o ;
            if (money.indexOf('+') == -1)
            {
                o = money.charAt(money.indexOf('-'));}
            else{
                o = money.charAt(money.indexOf('+'));}
            if (!(money.indexOf(o) == (money.length()-1)))
            {
                String num1 = money.substring(0,money.indexOf(o));
                String num2 = money.substring(money.indexOf(o)+1);
                float f1 = Float.parseFloat(num1),f2 = Float.parseFloat(num2);
                switch (o){
                    case '+':
                        money = String.valueOf(f1+f2)+operation;
                        break;
                    case '-':
                        money = String.valueOf(f1-f2)+operation;
                        break;
                    default:
                        break;
                }
            }
            else {
                money = money.substring(0, money.length() - 1);
            }
        }
        editText.setText(money);
        if(money.indexOf('+') == -1 && money.indexOf('-') == -1)
        {
            this.money = Float.parseFloat(money);
        }
    }
    private void myEqual(){
        String money = String.valueOf(editText.getText());
        char o;
        if (!(money.indexOf('+') == -1 && money.indexOf('-') == -1) ) {
            if (money.indexOf('+') == -1) {
                o = money.charAt(money.indexOf('-'));
            } else {
                o = money.charAt(money.indexOf('+'));
            }
            if (!(money.indexOf(o) == (money.length() - 1))) {
                String num1 = money.substring(0, money.indexOf(o));
                String num2 = money.substring(money.indexOf(o) + 1);
                float f1 = Float.parseFloat(num1), f2 = Float.parseFloat(num2);
                switch (o) {
                    case '+':
                        money = String.valueOf(f1 + f2);
                        break;
                    case '-':
                        money = String.valueOf(f1 - f2);
                        break;
                    default:
                        break;
                }
            } else {
                money = money.substring(0, money.length() - 1);
            }
        }
        editText.setText(money);
        this.money = Float.parseFloat(money);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn1:
                input(1);
                break;
            case R.id.btn2:
                input(2);
                break;
            case R.id.btn3:
                input(3);
                break;
            case R.id.btn4:
                backSpace();
                break;
            case R.id.btn5:
                input(4);
                break;
            case R.id.btn6:
                input(5);
                break;
            case R.id.btn7:
                input(6);
                break;
            case R.id.btn8:
                operation('-');
                break;
            case R.id.btn9:
                input(7);
                break;
            case R.id.btn10:
                input(8);
                break;
            case R.id.btn11:
                input(9);
                break;
            case R.id.btn12:
                operation('+');
                break;
            case R.id.btn13:
                clear();
                break;
            case R.id.btn14:
                input(0);
                break;
            case R.id.btn15:
                String money = String.valueOf(editText.getText());
                if (money.indexOf('.')==-1) {
                    money = money + ".";
                }
                editText.setText(money);
                break;
            case R.id.btn16:
                myEqual();
                break;
            default:
                break;
        }
    }
}
